package com.example.springboot_mvc_demo.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.example.springboot_mvc_demo.controller.OkHttpClientDemo;
import lombok.SneakyThrows;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * des:OkHttpUtils
 *
 * @author admin
 */
public class OkHttpUtils {
    private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);

    /**
     * 成功的code
     */
    public static final int SUCCESS_CODE = 200;


    private static volatile OkHttpClient okHttpClient = null;

    public static final ThreadLocal<OkHttpClient> CLIENT_THREAD_LOCAL =
            ThreadLocal.withInitial(OkHttpUtils::initOkHttpClient);

    private static volatile Semaphore semaphore = null;
    /**
     * head
     */
    private Map<String, String> headerMap;
    /**
     * 参数
     */
    private Map<String, Object> paramMap;
    /**
     * url
     */
    private String url;
    private Request.Builder request;

    /**
     * 初始化okHttpClient，并且允许https访问
     */
    private OkHttpUtils() {
        initOkHttpClient();
    }

    private static OkHttpClient initOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                    TrustManager[] trustManagers = buildTrustManagers();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
                            .hostnameVerifier((hostName, session) -> true)
                            .retryOnConnectionFailure(true)
                            .build();
                    //addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
                }
            }
        }
        return okHttpClient;
    }

    /**
     * 用于异步请求时，控制访问线程数，返回结果
     *
     * @return
     */
    private static Semaphore getSemaphoreInstance() {
        //只能1个线程同时访问
        synchronized (OkHttpUtils.class) {
            if (semaphore == null) {
                semaphore = new Semaphore(1);
            }
        }
        return semaphore;
    }

    /**
     * 创建OkHttpUtils
     *
     * @return
     */
    public static OkHttpUtils builder() {
        return new OkHttpUtils();
    }

    /**
     * 创建OkHttpUtils
     * 传入okHttpClient1 替换当前使用okhttp
     * 使用传入的client 发送本次请求
     * 这里的测试用例使用了 ribbon 来做负载均衡
     *
     * @return
     */
    public static OkHttpUtils builder(OkHttpClient okHttpClient) {
        CLIENT_THREAD_LOCAL.set(okHttpClient);
        return new OkHttpUtils();
    }

    /**
     * 添加url
     *
     * @param url
     * @return
     */
    public OkHttpUtils url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 添加参数
     *
     * @param key   参数名
     * @param value 参数值
     * @return
     */
    public OkHttpUtils addParam(String key, Object value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        String val = null;
        if (!ObjectUtils.isEmpty(value)) {
            val = value.toString();
        }
        paramMap.put(key, val);
        return this;
    }

    /**
     * 添加参数
     *
     * @param params 键值对参数
     * @return
     */
    public OkHttpUtils addParam(Map<String, Object> params) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        if (params == null) {
            return this;
        }
        paramMap.putAll(params);
        return this;
    }

    /**
     * 添加参数,然后全部转为 k,v都是string
     *
     * @param params 键值对参数
     * @return
     */
    public OkHttpUtils addParamToString(Map<String, Object> params) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>(16);
        }
        if (params == null) {
            return this;
        }
        Map<String, String> stringMap = params.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().toString()));
        paramMap.putAll(stringMap);
        return this;
    }


    /**
     * 添加请求头
     *
     * @param key   参数名
     * @param value 参数值
     * @return
     */
    public OkHttpUtils addHeader(String key, String value) {
        if (headerMap == null) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    /**
     * 初始化get方法
     * 示例：see {@link OkHttpClientDemo#getMsg()}
     *
     * @return
     */
    public OkHttpUtils get() {
        request = new Request.Builder().get();
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    if (ObjectUtils.isEmpty(entry.getValue())) {
                        continue;
                    }
                    String value = entry.getValue().toString();
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
                            append("=").
                            append(StrUtil.isNotBlank(value) ? URLEncoder.encode(value, "utf-8") : "").
                            append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            log.info("当前构造 get 访问url：{}", urlBuilder);

        }
        request.url(urlBuilder.toString());
        return this;
    }

    /**
     * 初始化post方法
     *
     * @param isJsonPost true等于json的方式提交数据，类似postman里post方法的raw
     *                   false等于普通的表单提交
     *                   示例：see {@link OkHttpClientDemo#listJson(Student)}
     * @return
     */
    public OkHttpUtils post(boolean isJsonPost) {
        RequestBody requestBody;
        if (isJsonPost) {
            String json = "";
            if (paramMap != null) {
                json = JSON.toJSONString(paramMap);
            }
            requestBody = RequestBody.create(OkHttpConstant.jsonType, json);
            // error Nu such
            //requestBody= RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (paramMap != null) {
                paramMap.forEach((k, v) -> {
                    if (ObjectUtils.isEmpty(v)) {
                        return;
                    }
                    formBody.add(k, v.toString());
                });
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    public OkHttpUtils post(RequestBody requestBody) {
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }



    /**
     * 构建文件传输的表单请求
     */
    public OkHttpUtils formFilePost() {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        paramMap.forEach((k, v) -> {
            addFormDataPart(k, v, builder);
        });
        return post(builder.build());
    }

    @SneakyThrows
    private void addFormDataPart(String k, Object v, MultipartBody.Builder builder) {



        if (v instanceof MultipartFile) {
            MultipartFile multipartFile = (MultipartFile) v;
            builder.addFormDataPart(k, multipartFile.getOriginalFilename(),
                    RequestBody.create(OkHttpConstant.multipartFileType, multipartFile.getBytes()));
            return;
        }
        builder.addFormDataPart(k, v.toString());
    }

    /**
     * 同步请求
     *
     * @return
     */
    public String sync() throws Exception {
        setHeader(request);
        try (Response response = CLIENT_THREAD_LOCAL.get().newCall(request.build()).execute()) {
            ResponseBody body = getBody(response);
            return body.string();
        } finally {
            CLIENT_THREAD_LOCAL.remove();
        }
    }

    /**
     * 同步请求
     *
     * @return
     */
    public Response getResponse() throws Exception {
        setHeader(request);
        Response response;
        try {
            response = CLIENT_THREAD_LOCAL.get().newCall(request.build()).execute();
            return response;
        } finally {
            CLIENT_THREAD_LOCAL.remove();
        }
    }

    /**
     * 同步请求
     *
     * @return
     */
    public byte[] syncInputStream() throws Exception {
        setHeader(request);
        try (Response response = CLIENT_THREAD_LOCAL.get().newCall(request.build()).execute()) {
            ResponseBody body = getBody(response);
            return body.bytes();
        } finally {
            CLIENT_THREAD_LOCAL.remove();
        }
    }

    /**
     * 同步请求
     *
     * @return
     */
    public <T> T sync(Class<T> type) throws Exception {
        setHeader(request);
        try (Response response = CLIENT_THREAD_LOCAL.get().newCall(request.build()).execute()) {
            ResponseBody body = getBody(response);
            String string = body.string();
            return JSON.parseObject(string, type, ParserConfig.global, JSON.DEFAULT_PARSER_FEATURE, null);
        } finally {
            CLIENT_THREAD_LOCAL.remove();
        }
    }

    public static ResponseBody getBody(Response response) throws Exception {
        ResponseBody body = response.body();
        if (SUCCESS_CODE != response.code()) {
            if (body != null) {
                log.error("error response :{}", body.string());
            }
            throw new RuntimeException("invalid http code :" + response.code());
        }
        if (body == null) {
            throw new NullPointerException("return empty response");
        }
        return body;
    }

    /**
     * 异步请求，有返回值
     * 这里回把值写入到 StringBuilder,当需要的时候，直接获取就行
     * 但是不能保证获取的时候一定有值
     * 如果要保证 那么需要使用阻塞获取值
     * 例子：修改返回值 为 单个队列(SynchronousQueue)，
     * 如果里面没有值,则阻塞，比如 queue.task()
     * 然后 回调函数使用 queue.put()即可
     * 不要使用 可能用完客户端的原因  导致有时候不能回调 拿不到结果值 会被一致阻塞。
     * TODO:后面修改为队列获取 因为队列只有一个 相当于是同步获取了，只有在调用队列的take方法时，才会获取值
     *
     * @return
     */
    @Deprecated
    public GetVal<String> async() {
        setHeader(request);
        GetVal<String> defaultGetVal = new DefaultGetVal();
        /**
         * 这个回调有点问题 有时候不能返回值 导致不能释放令牌。。
         */
        CLIENT_THREAD_LOCAL.get().newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                defaultGetVal.setError(e);
                log.error("onFailure ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //getSemaphoreInstance().release();
                log.info("un lock");
                try {
                    ResponseBody body = getBody(response);
                    defaultGetVal.setVal(body.string());
                } catch (Exception e) {
                    defaultGetVal.setError(e);
                    log.error("onResponse ", e);
                }
            }
        });
        try {
            log.info("wait lock {}", LocalTime.now());
            //getSemaphoreInstance().acquire();
            TimeUnit.MILLISECONDS.sleep(0);
            log.info("wait lock ok {}", LocalTime.now());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            CLIENT_THREAD_LOCAL.remove();
        }
        return defaultGetVal;
    }

    /**
     * 异步请求，带有接口回调
     *
     * @param callBack
     */
    public void async(ICallBack callBack) {
        setHeader(request);
        CLIENT_THREAD_LOCAL.get().newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                callBack.onSuccessful(call, response.body().string());
            }
        });
        CLIENT_THREAD_LOCAL.remove();
    }

    /**
     * 为request添加请求头
     *
     * @param request
     */
    private void setHeader(Request.Builder request) {
        if (headerMap != null) {
            try {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     *
     * @return
     */
    public static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }

    public static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    /**
     * 自定义一个接口回调
     */
    public interface ICallBack {

        void onSuccessful(Call call, String data);

        void onFailure(Call call, String errorMsg);

    }

    public interface SetVal<T> {
        /**
         * 设置返回值
         */
        public void setVal(T val);

        /**
         * 设置异常
         */
        public void setError(Exception e);
    }

    /**
     * 获取val的阻塞类
     * 默认使用使用 SynchronousQueue 阻塞 task 实现
     */
    public interface GetVal<T> extends SetVal<T> {
        /**
         * 获取返回值
         */
        public T syncGetVal() throws Exception;

    }

    @SuppressWarnings("unChecked")
    public static class DefaultGetVal implements GetVal<String> {
        BlockingQueue queue = new SynchronousQueue<String>();
        Exception exception;
        boolean hasError = false;

        @Override
        public String syncGetVal() throws Exception {
            Object remove = queue.take();
            if (remove instanceof Exception) {
                throw new RuntimeException((Exception) remove);
            }
            return (String) remove;
        }

        /**
         * SynchronousQueue的offer(e)方法总是返回false是正常现象，
         * 因为SynchronousQueue是一个同步队列，当生产者线程调用offer(e)方法时，
         * 如果没有其他消费者线程在等待接受数据，此时offer方法将会直接返回false，不会将元素插入到队列中。
         * 只有当消费者线程主动调用take()方法时，生产者线程的offer()方法才能将元素成功插入到队列中。
         */
        @Override
        public void setVal(String val) {
            try {
                queue.put(val);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void setError(Exception e) {
            exception = e;
            hasError = true;
            queue.add(null);
        }
    }

    /**
     *  常量
    */
    interface OkHttpConstant{
        /**
         *  文件表单
        */
        final static MediaType multipartFileType = MediaType.parse("multipart/form-data");
        /**
         *  json
        */
        final static MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
    }
}
